package es.mgil.cordova.plugins;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;

/**
 * Plugin para visualizar un contacto dado su ID
 * 
 * @author marc
 */
public class ContactView extends CordovaPlugin {
	private static final int VIEW_CONTACT = 1;
	private CallbackContext cbContext;

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		this.cbContext = callbackContext;
		startContactActivity(args.getInt(0));
		return true;
	}

	public void startContactActivity(int contactID) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI,
				String.valueOf(contactID));
		intent.setData(uri);
		cordova.startActivityForResult(this, intent, VIEW_CONTACT);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == 0) {
			switch (requestCode) {
			case (VIEW_CONTACT):
				this.cbContext.success();
				break;
			default:
				this.cbContext.error("Algo ha ido mal al mostrar el contacto");
				break;
			}
		} else {
			this.cbContext.error("No existe el contacto");
		}

		super.onActivityResult(requestCode, resultCode, intent);
	}
}